import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import moment from 'moment'
import style from './Style.module.less'
import { addResizeEvent, delResizeEvent } from '@redux/actions'
import ChartBlock from './ChartBlock'
import { Context } from './context'
import { strToNum } from '@src/assets/js/tool'

const defaultCauseAction = ['金融借款合同纠纷', '金融不良债权追偿纠纷', '融资租赁合同纠纷']

class AmountStatistic extends Component {
  getPercent (v) {
    const { total } = this.state
    if (v && total) {
      return Math.round(v / total * 10000) / 100 + '%'
    }
  }

  // 获取数据
  getData (year, causeaction, type) {
    const beginTime = Math.floor(moment(`${year}-01-01 00:00:00`).valueOf() / 1000)
    const endTime = Math.floor(moment(`${year}-12-31 23:59:59`).valueOf() / 1000)
    const actions = causeaction && causeaction.length ? causeaction.join() : defaultCauseAction.join()
    const condition = [{ k: type, o: '>=', v: beginTime }, { k: type, o: '<=', v: endTime }]
    return this.$get('/api/xapc/casestat/statCauseActionAll', {
      condition: JSON.stringify(condition),
      causeaction: actions
    }).then(res => {
      if (res.status !== 1) {
        throw new Error(res.message)
      }
      return {
        list: res.data.disputeamount,
        total: res.data.disputeamount.reduce((a, b) => ({ value: strToNum(a.value) + strToNum(b.value) })).value
      }
    })
  }

  // 获取echarts事件配置
  getEvents (y) {
    const actions = this.props.causeaction.length ? [...this.props.causeaction] : [...defaultCauseAction]
    const date = moment(`${y}-01-01 00:00:00`)
    const beginTime = moment(date)
    const endTime = moment(date)
    endTime.add(1, 'y')
    endTime.subtract(1, 's')
    return {
      click: (e) => {
        const type = this.props.type
        let useType = '包含'
        const formData = { type, beginTime, endTime }
        if (actions.indexOf(e.name) === -1) {
          useType = '不包含'
          formData.cause_action = actions
        } else {
          formData.cause_action = [e.name]
        }
        formData.cause_use_type = useType
        this.props.addWindow({ id: 'AllCaseManage', title: '仲裁案件列表', componentName: 'AllCaseManage', forceRefresh: true, meta: { formData } })
      }
    }
  }

  // componentDidMount () {
  //   this.props.addResizeEvent({
  //     name: 'finance-AmountStatistic',
  //     handle: () => this.setState({ ready: false }, () => {
  //       setTimeout(() => {
  //         this.setState({ ready: true })
  //       }, 100)
  //     })
  //   })
  // }

  // componentWillUnmount () {
  //   this.props.delResizeEvent('finance-AmountStatistic')
  // }

  render () {
    const { causeaction, searchVersion, type } = this.props
    let height = 240
    if (causeaction.length > 4) {
      height = 240 + (causeaction.length - 3) * 44
    }
    const getData = (...args) => this.getData(...args)
    return (
      <div className={style.block}>
        <div className={style['block-header']}>
          <span className={style['block-header__title']}>标的维度</span>
        </div>
        <div className={style['block-body']}>
          <Context.Consumer>
            {({ yearOne, changeYearOne }) => (
              <ChartBlock type='disputeamount' height={height} year={yearOne} changeYear={changeYearOne} getData={getData} getEvents={year => this.getEvents(year)} searchVersion={searchVersion} causeaction={causeaction} timeType={type} />
            )}
          </Context.Consumer>
          <Context.Consumer>
            {({ yearTwo, changeYearTwo }) => (
              <ChartBlock type='disputeamount' height={height} year={yearTwo} changeYear={changeYearTwo} getData={getData} getEvents={year => this.getEvents(year)} searchVersion={searchVersion} causeaction={causeaction} timeType={type} />
            )}
          </Context.Consumer>
          <Context.Consumer>
            {({ yearThree, changeYearThree }) => (
              <ChartBlock type='disputeamount' height={height} year={yearThree} changeYear={changeYearThree} getData={getData} getEvents={year => this.getEvents(year)} searchVersion={searchVersion} causeaction={causeaction} timeType={type} />
            )}
          </Context.Consumer>
        </div>
      </div>
    )
  }
}

AmountStatistic.proptypes = {
  causeaction: PropTypes.array,
  type: PropTypes.string,
  searchVersion: PropTypes.number
}

AmountStatistic.defaultProps = {
  causeaction: [],
  type: '',
  searchVersion: Date.now()
}

const mapState = mapStateToProps(function (state) {
  return {

  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {
    addResizeEvent: i => dispatch(addResizeEvent(i)),
    delResizeEvent: i => dispatch(delResizeEvent(i))
  }
})

export default connect(mapState, mapDispatch)(AmountStatistic)
